<template>
  <div class="vendorOrderTotal">
    <!-- 厂商订货合计 -->
    <div class="topbar">
      <p>厂商</p>
      <el-select class="top-inp" v-model="manufacturer" clearable multiple collapse-tags @change="manufacturerChange">
        <el-option v-for="item in manufacturerList" :key="item.value" :label="item.label" :value="item.value">
          <span style="float:left">{{item.value}}</span>
          <span style="float:right">{{item.label}}</span></el-option>
      </el-select>
      <p>品牌</p>
      <el-select class="top-inp" v-model="brandedName">
        <el-option v-for="item in brandList" :key="item.value" :label="item.label" :value="item.value"></el-option>
      </el-select>
      <p>品名</p>
      <el-select class="top-inp" v-model="commodityName">
        <el-option v-for="item in commodityNameList" :key="item.value" :label="item.label" :value="item.value"></el-option>
      </el-select>
      <p>货号</p>
      <el-input v-model="kindsNumber" clearable></el-input>
      <p style="margin-left:0.5vw">未交数量</p>
      <el-input v-model="unpaidNumber">
        <template slot="prepend">>=</template></el-input>
      <p>季度</p>
      <el-select v-model="quarter" clearable multiple collapse-tags>
        <el-option v-for="item in quarterList" :key="item.value" :label="item.label" :value="item.value"></el-option>
      </el-select>
      <p class="t_content">日期</p>
      <el-date-picker unlink-panels v-model="dateList" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd"></el-date-picker>
    </div>
    <div class="operation">
      <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
      <el-button icon="el-icon-printer" @click="openPrint(1,'printTable')">列印</el-button>
      <span>合计方式
        <el-select class="top-inp" v-model="summarization">
          <el-option v-for="item in summarizationList" :key="item.value" :label="item.label" :value="item.value"></el-option></el-select>
      </span>
    </div>
    <el-table id="outtable" :data="tableData" style="width: 100%" height="75.5vh" :header-cell-style="{background:'#f4f4f4',padding:0,height:'40px'}" :cell-style="{padding:0,height:'36px'}">
      <el-table-column prop="manufacturerNo" label="厂商编号" sortable v-if="summarization != 4 && summarization != 5"></el-table-column>
      <el-table-column prop="manufacturerName" label="厂商简称" sortable v-if="summarization != 4 && summarization != 5"></el-table-column>
      <el-table-column prop="kindsNumber" label="货号" sortable v-if="summarization != 3 && summarization != 5"></el-table-column>
      <el-table-column prop="styleNumber" label="款号" sortable v-if="summarization == 3 || summarization == 5"></el-table-column>
      <el-table-column prop="unpaidQuantity" label="未交数量" sortable></el-table-column>
      <el-table-column prop="orderAmount" label="订货数量" sortable></el-table-column>
      <el-table-column prop="additionalQuantity" label="追加数量" sortable></el-table-column>
      <el-table-column prop="purchaseQuantity" label="进货数量" sortable></el-table-column>
      <el-table-column prop="returnedQuantity" label="退货数量" sortable></el-table-column>
    </el-table>
    <foot-view class="footView" :pagesNum="pagesNum" :hasPagination=true :pageSize="limit" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange">
      <div slot="text">
        <span>数据库：{{jxQuarter}}</span></div>
    </foot-view>
    <div id="p" v-show=false></div>
  </div>
</template>

<script>
const resources = require('../../../config/printCSS3')

import footView from '../../../components/FootView'

import { getManufacturer } from '../../../network/manufacturer'
import { getQuarter } from '../../../network/quarter'
import { getBranded } from '../../../network/branded'
import { getProductName } from '../../../network/productName'
import { totalQuery } from '../../../network/manufacturerOrder'
import { getSystemConfig } from '../../../network/operatoryCommand'

import today from '../../../components/mixins/today'
import enterUp from '../../../components/mixins/enterUp'

export default {
  name:'vendor_order_goods_total',
  mixins: [today,enterUp],
  created(){

    let jxQuarterVal = document.cookie.match(RegExp('jxQuarter' + '=([^;]+)'))
    let operatorVal = document.cookie.match(RegExp('jxAgent'+'=([^;]+)'))
    this.jxQuarter = jxQuarterVal ? jxQuarterVal[1] : null
    this.operator = operatorVal ? operatorVal[1] : null



    this.inpList = this.getInput()
    // 默认选之前一周
    // this.dateList = [this.searchDate(7),this.searchDate()]
    // 获取季度
    getQuarter().then(res => {
      if (res.data.code == 200) {
        res.data.data.forEach(e => {
          this.quarterList.push({value:e.id,label:e.name})
        })
      }
    })
    // 获取厂商信息
    getManufacturer({limit:9999}).then(res=>{
      if (res.data.code == 200) {
        let list = res.data.data
        list.forEach(e => {
          this.manufacturerList.push({
            value:e.no,label:e.name,
            contact:e.contact,phone:e.phone,
            address:e.address})
        })
      }
    })
    // 获取品牌
    getBranded().then(res => {
      res.data.data.forEach(e => {
        this.brandList.push({value:e.name,label:e.name})
      })
    })
    // 获取品名信息
    getProductName().then(res => {
      if (res.data.code == 200) {
        let list = res.data.data
        list.forEach(e => {
          this.commodityNameList.push({value:e.name,label:e.name})
        })
      }
    })
    getSystemConfig().then(res => {
      if (res.data.data) {
        this.printVendor = res.data.data.companyName
      }
    })
  },
  data(){
    return {
      inpList: [],
      props: { multiple: true },
      
      manufacturer: [],
      manufacturerList: [],
      brandedName: '',
      brandList: [],
      commodityName: '',
      commodityNameList: [],
      unpaidNumber: '',
      kindsNumber: '',
      quarter: [],
      quarterList: [],
      dateList: null,
      
      summarization: 1,
      summarizationList: [
        {value: 1, label: '不合计'},
        {value: 2, label: '厂商合计'},
        {value: 3, label: '厂商-款号合计'},
        {value: 4, label: '货号合计'},
        {value: 5, label: '款号合计'},
      ],
      tableData: [],
      allData: [],

      // 总数据条数
      dataLen: 0,
      // 总页码
      pagesNum: 0,
      // 分页条数
      limit: 20,
      // 当前页码
      currentPage: 1,
      jxQuarter: null,
      operator:null,
      // jxQuarter: document.cookie.match(RegExp('jxQuarter'+'=([^;]+)'))[1],
      // operator: document.cookie.match(RegExp('jxUser'+'=([^;]+)'))[1],

      printVendor: '',
      printManu: '',
      sum1: 0,
      sum2: 0,
      sum3: 0,
      sum4: 0,
      sum5: 0,
      printToday: this.searchDate(),
      printContact: '',
      printPhone: '',
      printAddress: ''
    }
  },
  watch: {
    summarization(a,b){
      this.search()
    },
    dataLen(a,b){
      this.pagesNum = Math.ceil(this.dataLen / this.limit)
    },
    limit(a,b){
      this.pagesNum = Math.ceil(this.dataLen / this.limit)
    }
  },
  components: {
    footView
  },
  methods: {
    search(){
      let knList = []
      if (this.kindsNumber) {
        knList = this.kindsNumber.split(',')
      }
      
      let d = {
        manufacturerNoList: this.manufacturer,
        brandedName: this.brandedName,
        commodityName: this.commodityName,
        kindsNumberList: knList,
        unpaidNumber: this.unpaidNumber,
        quarterList: this.quarter,
        startTime: (this.dateList == '' || this.dateList == null) ? '' : this.dateList[0] + ' 00:00:00',
        endTime: (this.dateList == '' || this.dateList == null) ? '' : this.dateList[1] + ' 23:59:59',
        totalWay: this.summarization,
        pageData: {
          limit: this.limit,
          page: this.currentPage
        }
      }
      totalQuery(JSON.stringify(d)).then(res => {
        if (res.data.data.length) {
          res.data.data.forEach(e => {
            for (const i of this.manufacturerList) {
              if (i.value == e.manufacturerNo) {
                e.manufacturerName = i.label
                break
              }
            }
          })
        }
        this.currentPage = 1
        this.dataLen = res.data.total
        this.allData = res.data.data
        this.tableData = res.data.data

        this.allData.forEach(e => {
          for (const key in e) {
            if (Object.hasOwnProperty.call(e, key)) {
              const element = e[key];
              if (!element) {
                e[key] = ''
              }
            }
          }
        })
      })
    },

    // 每页显示页数改变
    handleSizeChange(val){
      this.limit = val
      this.currentPage = 1
      this.search()
    },
    // 当前页改变
    handleCurrentChange(val){
      this.currentPage = val
      this.search()
    },

    manufacturerChange(e){
      // console.log(e)
      if (!e.length) return
      this.printManu = ''
      this.printContact = ''
      this.printPhone = ''
      this.printAddress = ''
      for (const i of this.manufacturerList) {
        if (i.value == e[0]) {
          this.printManu = i.label
          this.printContact = i.contact
          this.printPhone = i.phone
          this.printAddress = i.address
          return
        }
      }
    },

    openPrint(x, id){
      if (!this.allData.length) return
      if (x == 1) {
        document.getElementById('p').innerHTML = ''
      }
      let printHead = document.createElement('div')
      printHead.classList.add("addPrintHead")
      printHead.innerHTML = `
        <p class="printTitle">${this.printVendor}${this.jxQuarter}厂商订货合计</p>
        <div class="info">
          <p>厂商：${this.printManu}</p>
          <p>联系人：${this.printContact}</p>
          <p>电话：${this.printPhone}</p>
          <p>打印日期：${this.printToday}</p>
        </div>
        <div class="info">
          <p>厂商地址：${this.printAddress}</p>
        </div>
      `
      let printTable = document.createElement('table')
      printTable.id = id
      printTable.align = "center"
      printTable.innerHTML = `
        <tr>
          <td style="width:4%">序号</td>
          <td style="width:15%">厂商简称</td>
          <td style="width:20%">货号</td>
          <td>未交数量</td>
          <td>订货数量</td>
          <td>取消数量</td>
          <td>进货数量</td>
          <td>退货数量</td>
        </tr>
      `
      let p = document.getElementById('p')
      p.appendChild(printHead)
      p.appendChild(printTable)

      let index = --x
      let length = this.allData.length
      // console.log(index, length)
      
      for (index; index < length; index++) {
        const e = this.allData[index]
        this.sum1 += Number(e.unpaidQuantity)
        this.sum2 += Number(e.orderAmount)
        this.sum3 += Number(e.additionalQuantity)
        this.sum4 += Number(e.purchaseQuantity)
        this.sum5 += Number(e.returnedQuantity)

        let row = printTable.insertRow(printTable.FetchRowCount)
        row.insertCell(0).innerHTML = index+1
        row.insertCell(1).innerHTML = e.manufacturerName
        row.insertCell(2).innerHTML = e.kindsNumber
        row.insertCell(3).innerHTML = e.unpaidQuantity
        row.insertCell(4).innerHTML = e.orderAmount
        row.insertCell(5).innerHTML = e.additionalQuantity
        row.insertCell(6).innerHTML = e.purchaseQuantity
        row.insertCell(7).innerHTML = e.returnedQuantity

        if (parseInt((index+1)/35) && (index+1)%35 == 0 && (index+1) != length) {
          // console.log('35倍数')
          let pageIndex = index + 2 - (parseInt(index/35)*35)
          // console.log(pageIndex)
          // console.log(index+1)    // 35
          // console.log(length)     // 36
          let startingPoint = index - 34
          let s1 = 0
          let s2 = 0
          let s3 = 0
          let s4 = 0
          let s5 = 0
          for (let j = startingPoint; j <= index; j++) {
            s1 += this.allData[j].unpaidQuantity
            s2 += this.allData[j].orderAmount
            s3 += this.allData[j].additionalQuantity
            s4 += this.allData[j].purchaseQuantity
            s5 += this.allData[j].returnedQuantity
          }

          let rowEnd = printTable.insertRow(printTable.FetchRowCount)
          rowEnd.insertCell(0).innerHTML = '本页小计：'
          printTable.rows[pageIndex].cells[0].colSpan = '3'
          rowEnd.insertCell(1).innerHTML = Math.ceil(s1)
          rowEnd.insertCell(2).innerHTML = Math.ceil(s2)
          rowEnd.insertCell(3).innerHTML = Math.ceil(s3)
          rowEnd.insertCell(4).innerHTML = Math.ceil(s4)
          rowEnd.insertCell(5).innerHTML = Math.ceil(s5)

          let lineFeed = document.createElement('div')
          lineFeed.style.pageBreakBefore = 'always'
          p.appendChild(lineFeed)

          let tableId = `printTable${(index+1)/35}`
          // console.log(tableId)
          // console.log(index)
          this.openPrint(index+2,tableId)
          return
        }
        if ((index+1) == length) {
          let pageIndex = index + 2 - (parseInt(index/35)*35)
          // console.log('最后一行')
          let startingPoint = index < 35 ? 0 : parseInt(index/35)*35

          let rowEnd = printTable.insertRow(printTable.FetchRowCount)
          rowEnd.insertCell(0).innerHTML = '合计：'
          printTable.rows[pageIndex].cells[0].colSpan = '3'
          rowEnd.insertCell(1).innerHTML = this.sum1
          rowEnd.insertCell(2).innerHTML = this.sum2
          rowEnd.insertCell(3).innerHTML = this.sum3
          rowEnd.insertCell(4).innerHTML = this.sum4
          rowEnd.insertCell(5).innerHTML = this.sum5

          let printFoot = document.createElement('div')
          printFoot.classList.add("addPrintHead")
          printFoot.innerHTML = `
            <div class="info">
              <p>电话：</p>
              <p>传真：</p>
            </div>
            <div class="info">
              <p>操作员：${this.operator}</p>
              <p>主管：</p>
              <p>财务：</p>
              <p>复核：</p>
            </div>
            <div class="info">
              <p>备注：</p>
            </div>
          `
          p.appendChild(printFoot)
        }
      }

      // console.log(this.styleList)
      let int = setInterval(() => {
        clearInterval(int)
        let printHtml = document.getElementById('p').innerHTML
        let wind = window.open("",'newwindow', 'height=500, width=1000, top=100, left=100, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no')
        wind.document.body.innerHTML = printHtml
        let style = document.createElement('style')
        style.type = 'text/css'
        style.innerHTML = resources.printCSS
        wind.document.head.appendChild(style)
        wind.print()
        return false
      }, 500)
    }
  }
}
</script>


<style scoped>
  .vendorOrderTotal {
    margin-right: 0.5vw;
    padding: 0 15px;
    background-color: white;
    height: 95vh;
    position: relative;
  }
  /* 头部 */
  .topbar{
    white-space: nowrap;
    border-bottom: 2px solid #f4f4f4;
    position: relative;
    padding: 1.5vh 0;
  }
  .topbar p{
    display: inline-block;
    margin-right: 0.5vw;
    line-height: 30px;
  }

  /* 按钮 */
  .operation{
    padding: 1.5vh 0;
    white-space: nowrap;
  }
  .operation span{
    float: right;
    white-space: nowrap;
  }

  .footView span{
    float: left;
    margin-right: 48px;
    line-height: 6vh;
    font-size: 14px;
  }

</style>

<style>
  .vendorOrderTotal .topbar .el-input{
    width: 8vw;
  }
  .vendorOrderTotal .el-input__inner{
    height: 30px!important;
  }
  .vendorOrderTotal .el-select{
    width: 8vw;
    margin-right: 10px;
  }
  .vendorOrderTotal .el-button{
    padding: 8px 15px;
    height: 30px;
  }
  .vendorOrderTotal .el-date-editor {
    width: 300px;
  }

  .vendorOrderTotal .el-input__icon , .vendorOrderTotal .el-date-editor .el-range-separator{
    line-height: 22px;
  }

  .vendorOrderTotal .el-range-editor .el-range-input{
    width: 100px;
  }
  .vendorOrderTotal .el-date-editor .el-range-separator{
    width: 11%;
  }
  .vendorOrderTotal .el-select__tags, .vendorOrderTotal .el-cascader__tags {
    top: 66%;
  }
  .vendorOrderTotal .el-cascader__tags .el-tag{
    max-width: 64%;
  }
  .vendorOrderTotal .el-cascader{
    line-height: 30px;
  }
</style>